#!/usr/bin/perl

use strict;
use Net::Netrc;

use WWW::NikePlus;
use Toolkit;

my $mach = Net::Netrc->lookup('nikeplus');

my $np = WWW::NikePlus->new(
  login    => $mach->login(),
  password => $mach->password()
);

my @positions = qw( 1 5 10 25 50 100 );

my @table = (['Challenge', 'Rank', @positions]);

foreach my $challenge ($np->get_challenge_list(active => 1)) {
  next unless( $challenge->getType() =~ /distance/io );
  my $rank = $challenge->getRank();

  my $lower = $rank - 100;
  $lower = 0 if($lower < 0);

  my @members = $challenge->getMembers(start => $lower, end => $rank);
  @members = reverse(@members);

  if( $lower > 100 ){
    my @temp = $challenge->getMembers(start => ($lower-100), end => ($lower-1));
    @temp = reverse(@temp);
    push(@members, @temp);
  }

  my $name = $challenge->getName();
  if(length($name) > 33) {
    $name = substr($name, 0, 30);
    $name .= '...';
  }

  my $me = $members[0];
  my $row = [$name, $rank . '/' . int($me->{'progress'} * 0.621371192)];
  foreach my $offset (@positions) {
    my $i;
    my $them = $members[$offset];

    if( defined($them) ){
      $i = ($them->{'progress'} - $me->{'progress'}) * 0.621371192;
      $i = sprintf('%.02f', $i);
    }
    push(@{$row}, $i);
  }

  push(@table, $row);
}
dump_table(table => \@table, sort => 0);
